﻿using System;
using System.Collections.Generic;
using Gumini.JulaDB.DataTypes;

namespace Gumini.JulaDB.Expressions
{
    /// <summary>
    /// Represents a leaf in the expression tree containing a typed non-null constant value.
    /// </summary>
    internal class Constant : Expression
    {
        readonly object _value;
        readonly DataType _type;

        public Constant(object value)
            : base()
        {
            _type = DataType.GetType(value.GetType());
            // we might need to convert the value e.g. from int to decimal so we have uniform representation of all numbers
            _value = _type.ConvertFrom(value);
        }

        public override TypedValue Evaluate(List<Context<TypedValue>> context)
        {
            return new TypedValue(_type, _value);
        }

        public override DataType InferType(Context<DataType> context)
        {
            return _type;
        }

        public override bool Equals(Expression other)
        {
            var b = other as Constant;
            if (b == null)
                return false;
            return
                this._type.Equals(b._type) &&
                this._value.Equals(b._value);
        }

        public override string ToString()
        {
            return String.Format("{0}:{1}", _value, _type);
        }
    }
}
